package com.atguigu.guli.service.ucenter.service.impl;

import com.atguigu.guli.common.util.FormUtils;
import com.atguigu.guli.common.util.HttpClientUtils;
import com.atguigu.guli.common.util.MD5;
import com.atguigu.guli.service.base.consts.ServiceConsts;
import com.atguigu.guli.service.base.exception.GuliException;
import com.atguigu.guli.service.base.result.ResultCodeEnum;
import com.atguigu.guli.service.base.utils.JwtHelper;
import com.atguigu.guli.service.base.utils.JwtInfo;
import com.atguigu.guli.service.ucenter.entity.Member;
import com.atguigu.guli.service.ucenter.entity.form.RegisterForm;
import com.atguigu.guli.service.ucenter.mapper.MemberMapper;
import com.atguigu.guli.service.ucenter.service.MemberService;
import com.atguigu.guli.service.ucenter.util.UcenterProperties;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 会员表 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2021-08-09
 */
@Service
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements MemberService {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    private UcenterProperties ucenterProperties;
    @Override
    public void regist(RegisterForm registerForm) {
        String code = registerForm.getCode();
        String mobile = registerForm.getMobile();
        String nickname = registerForm.getNickname();
        String password = registerForm.getPassword();
        //形参所带参数是否正确
        if(StringUtils.isEmpty(code)||StringUtils.isEmpty(mobile)
                ||StringUtils.isEmpty(nickname)||StringUtils.isEmpty(password)
                || !FormUtils.isMobile(mobile)){
            throw new GuliException(ResultCodeEnum.PARAM_ERROR,new RuntimeException("参数错误"));
        }
        String perminKey = ServiceConsts.MOBEL_CODE_PERFIX +mobile;
        Object codeObj = redisTemplate.opsForValue().get(perminKey);
        //验证码是否正确
        if(codeObj==null||!code.equals(codeObj.toString())){
            throw new GuliException(ResultCodeEnum.CODE_ERROR,new RuntimeException("验证码错误"));
        }
        LambdaQueryWrapper<Member> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(Member::getMobile,mobile);
        Integer count = baseMapper.selectCount(queryWrapper);
        //查看手机是否已被注册
        if(count>0){
            throw new GuliException(ResultCodeEnum.REGISTER_MOBLE_ERROR,new RuntimeException("手机已被注册"));
        }
        Member member =new Member();
        member.setMobile(mobile);
        member.setNickname(nickname);
        member.setAvatar("https://sh0325-gulipro.oss-cn-shanghai.aliyuncs.com/avatar/2021/08/01/5de84ad0-920e-43d8-a32f-1528019d503b.jpg");
        member.setDisabled(false);
        member.setPassword(MD5.encrypt(password));
        baseMapper.insert(member);
    }

    @Override
    public String login(String mobile, String password) {
        if(StringUtils.isEmpty(mobile)||StringUtils.isEmpty(password)||!FormUtils.isMobile(mobile)){
            throw new GuliException(ResultCodeEnum.PARAM_ERROR);
        }
        QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile",mobile);
        Member member = baseMapper.selectOne(queryWrapper);
        if(member==null){
            throw new GuliException(ResultCodeEnum.LOGIN_MOBILE_ERROR);
        }
        if(!MD5.encrypt(password).equals(member.getPassword())){
            throw new GuliException(ResultCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        if(member.getDisabled()){
            throw new GuliException(ResultCodeEnum.LOGIN_DISABLED_ERROR);
        }
        JwtInfo jwtInfo = new JwtInfo();
        jwtInfo.setAvatar(member.getAvatar());
        jwtInfo.setId(member.getId());
        jwtInfo.setNickname(member.getNickname());
        String token = JwtHelper.createToken(jwtInfo);
        return token;
    }

    @Override
    public String wxlogin(HttpSession session) {   //baseurl字符串可以用%s作为占位符，然后用String.format(baserurl,)后面家需要填充的字符串，不用内网穿透是因为自己调用，可以直接用localhost
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect?" +
                "appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect ";
        try {

            String redirectUri = URLEncoder.encode(ucenterProperties.getRedirectUri(), "UTF-8");
            String appid = ucenterProperties.getAppId();
            String state = UUID.randomUUID().toString().replace("-","");
            session.setAttribute("wx_open_state",state);
            baseUrl = String.format(baseUrl,appid,redirectUri,state);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:" + baseUrl;
    }

    @Override
    public String callback(String code, String state, HttpSession session) {
        try {
            Object stateObj = session.getAttribute("wx_open_state");
            if(stateObj==null|| StringUtils.isEmpty(state)||!state.equals(stateObj.toString())){
                throw new GuliException(ResultCodeEnum.ILLEGAL_CALLBACK_REQUEST_ERROR);
            }

            String url = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
                    "appid="+ucenterProperties.getAppId() +
                    "&secret="+ucenterProperties.getAppSecret() +
                    "&code="+code +
                    "&grant_type=authorization_code";

            HttpClientUtils httpClientUtils = new HttpClientUtils(url);
            httpClientUtils.get(); //发送get请求，返回appid和token
            String content = httpClientUtils.getContent();
            Map map = new Gson().fromJson(content, Map.class);

            if(map.get("errcode")!=null){
                throw new GuliException(ResultCodeEnum.ILLEGAL_CALLBACK_REQUEST_ERROR);
            }
            String openid = map.get("openid").toString();
            String accessToken = map.get("access_token").toString();
            QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("openid",openid);
            Member member = baseMapper.selectOne(queryWrapper);
            if(member==null){
                url = "https://api.weixin.qq.com/sns/userinfo?" +
                        "access_token="+ accessToken +
                        "&openid="+openid;   //返回用户基本信息
                httpClientUtils = new HttpClientUtils(url);
                httpClientUtils.get();
                map = new Gson().fromJson(httpClientUtils.getContent(), Map.class);
                System.out.println(map);
                if(map.get("errcode")!=null){
                    throw new GuliException(ResultCodeEnum.ILLEGAL_CALLBACK_REQUEST_ERROR);
                }
                String nickname = map.get("nickname").toString();
                int sex = new BigDecimal(map.get("sex").toString()).intValue();
                String headimgurl = map.get("headimgurl").toString();
                member = new Member();
                member.setNickname(nickname);
                member.setOpenid(openid);
                member.setSex(sex);
                member.setAvatar(headimgurl);
                baseMapper.insert(member);

            }

            String nickname = member.getNickname();
            String headimgurl = member.getAvatar();
            String id = member.getId();


            JwtInfo jwtInfo = new JwtInfo();
            jwtInfo.setNickname(nickname);
            jwtInfo.setAvatar(headimgurl);
            jwtInfo.setId(id);
            String token = JwtHelper.createToken(jwtInfo);
            return "redirect:http://localhost:3000?token="+token;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public Integer countRegisterMember(String date) {
        QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("DATE(gmt_create)",date);
        Integer count = baseMapper.selectCount(queryWrapper);
        return count;
    }
}
